import {messages} from "share/common";
import React from 'react';
import {connect} from 'react-redux';
import {Table, message, Tabs, Popconfirm, Icon} from 'antd';
import {SelectDepOrPerson} from 'components/index'
import RSService from 'containers/setting/role-setting/role-setting.service'
import 'styles/setting/role-setting/admin-role/admin-role.scss';
const TabPane = Tabs.TabPane;
import ResizeTable from "components/resize-table";

class RoleSettingAdmin extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      tab: 'tenant',
      columns: [
        {
          title: messages('common.sequence'),
          dataIndex: 'index',
          width: '10%',
          render: (value, record, index) =>
            this.state.pageSize * this.state.page + index + 1
        },
        {
          title: messages('setting.key886'/*工号*/),
          dataIndex: 'employeeID'
        },
        {
          title: messages('setting.key887'/*姓名*/),
          dataIndex: 'fullName'
        },
        {
          title: messages('setting.key888'/*部门*/),
          dataIndex: 'department',
          render: value => value && value.name ? value.name : ""
        },
        {
          title: messages('common.operation'),
          dataIndex: 'userOID',
          width: '10%',
          render: value => {
            const {tab, authorities} = this.state;
            return ((tab === 'tenant' && this.props.tenantMode && authorities.indexOf('ROLE_TENANT_ADMIN') !== -1) ||
              tab === 'company') ? (
              <Popconfirm onConfirm={() => this.handleDelete(value)}
                          title={messages('common.confirm.delete')}>
                <a onClick={e => {
                  e.preventDefault();
                  e.stopPropagation()
                }}>{messages('common.delete')}</a>
              </Popconfirm>
            ) : '-'
          }
        }
      ],
      data: [],
      pagination: {
        total: 0
      },
      page: 0,
      pageSize: 10,
      authorities: this.props.user.authorities
    };
  }

  componentDidMount() {
    this.getList()
  }

  getList = () => {
    const {tab, page, pageSize} = this.state;
    let roleName = tab === 'tenant' ? 'ROLE_TENANT_ADMIN' : 'ROLE_COMPANY_ADMIN';
    let params = {
      page, size: pageSize
    };
    this.setState({loading: true});
    RSService.getRoleUserListByRoleName(roleName, params).then(res => {
      this.setState({
        loading: false,
        data: res.data || [],
        pagination: {
          total: Number(res.headers['x-total-count']) || 0,
          onChange: this.onChangePager,
          current: this.state.page + 1
        }
      })
    }).catch(() => {
      this.setState({loading: false})
    })
  };

  onChangePager = (page) => {
    if (page - 1 !== this.state.page)
      this.setState({page: page - 1}, () => {
        this.getList()
      })
  };

  onChangeTabs = (tab) => {
    this.setState({tab, page: 0}, () => {
      this.getList()
    })
  };

  handleAdd = (result) => {
    let authorityName = this.state.tab === 'tenant' ? 'ROLE_TENANT_ADMIN' : 'ROLE_COMPANY_ADMIN';
    let userOIDs = [];
    result.map(item => {
      userOIDs.push(item.userOID)
    });
    let params = {authorityName, userOIDs};
    this.setState({loading: true});
    RSService.addRoleUser(params).then(() => {
      message.success(messages('common.operate.success'));
      this.getList()
    })
  };

  handleDelete = (OID) => {
    let authorityName = this.state.tab === 'tenant' ? 'ROLE_TENANT_ADMIN' : 'ROLE_COMPANY_ADMIN';
    let params = {
      authorityName,
      userOIDs: [OID]
    };
    RSService.deleteRoleUser(params).then(() => {
      this.getList()
    })
  };

  goBack = () => {
    this.context.router.goBack()
  };

  render() {
    const {loading, tab, columns, data, pagination, authorities} = this.state;
    const {tenantMode} = this.props;
    return (
      <div className="setting-role-setting-admin">
        <Tabs onChange={this.onChangeTabs} activeKey={tab}>
          <TabPane tab={messages('setting.key889'/*集团管理员*/)} key='tenant'/>
          <TabPane tab={messages('setting.key890'/*公司管理员*/)} key='company'/>
        </Tabs>
        <div className="table-header">
          {((tab === 'tenant' && tenantMode && authorities.indexOf('ROLE_TENANT_ADMIN') !== -1) ||
            tab === 'company') && (
            <SelectDepOrPerson buttonType="primary"
                               title={messages('common.add')}
                               onlyPerson={true}
                               onConfirm={this.handleAdd}/>
          )}
          <div className="table-header-title">{messages('common.total', {total: pagination.total})}</div>
        </div>
        <ResizeTable
          loading={loading}
          columns={columns}
          dataSource={data}
          pagination={pagination}
          size="middle"
          bordered
          rowKey={record => record.id}
        />
        <a className="back" onClick={this.goBack}>
          <Icon type="rollback" style={{marginRight: 5}}/>
          {messages('common.back')}
        </a>
      </div>
    )
  }
}

RoleSettingAdmin.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    user: state.login.user,
    tenantMode: state.main.tenantMode
  }
}

export default connect(mapStateToProps)(RoleSettingAdmin);
